package u.can.i.up.db.mysql;

import java.io.Reader;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class ReadMysql {
	public static void readDownload(Map<String, Long> packageDownloadNumberMap,
			Map<String, String> packageCategoryMap) {

		Reader reader;
		try {
			reader = Resources.getResourceAsReader("MybatisConfig.xml");
			SqlSessionFactoryBuilder ssfBuilder = new SqlSessionFactoryBuilder();
			SqlSessionFactory sqlSessionFactory = ssfBuilder.build(reader, "mysql");
			SqlSession sqlSession = sqlSessionFactory.openSession();
			DownloadNumberDAO downloadDAO = sqlSession.getMapper(DownloadNumberDAO.class);

			List<AppDownload> officialAppsList = downloadDAO.getDownloadNumberOfficial();
			List<AppDownload> unofficialAppsList = downloadDAO.getDownloadNumberUnofficial();

			for (AppDownload app : officialAppsList) {
				String url = app.getUrl();
				int start = url.indexOf("?id=");
				if (start != -1) {
					start += 4;
					int end;
					String app_name = "";
					if ((end = url.indexOf("&feature")) == -1) {
						app_name = url.substring(start);
					} else {
						app_name = url.substring(start, end);
					}
					if (!packageCategoryMap.containsKey(app_name)) {
						packageCategoryMap.put(app_name, app.getCategory());
					}

					if (packageDownloadNumberMap.containsKey(app_name)) {
						packageDownloadNumberMap.put(app_name,
								packageDownloadNumberMap.get(app_name) + app.getDownload_floor());
					} else {
						packageDownloadNumberMap.put(app_name, app.getDownload_floor());
					}
				}
			}
			for (AppDownload app : unofficialAppsList) {
				if (packageCategoryMap.containsKey(app.getPackage_name())
						|| packageDownloadNumberMap.containsKey(app.getPackage_name())) {
					if (packageDownloadNumberMap.get(app.getPackage_name()) != null
							&& app.getDownload_floor() != null) {
						packageDownloadNumberMap.put(app.getPackage_name(),
								packageDownloadNumberMap.get(app.getPackage_name()) + app.getDownload_floor());
					} else if (app.getDownload_floor() == null) {
					} else if (packageDownloadNumberMap.get(app.getPackage_name()) == null
							&& app.getDownload_floor() != null) {
						packageDownloadNumberMap.put(app.getPackage_name(), app.getDownload_floor());
					}
				} else {
					packageDownloadNumberMap.put(app.getPackage_name(), app.getDownload_floor());
					packageCategoryMap.put(app.getPackage_name(), app.getCategory());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
